package com.xbongbong.paas.script.i18n;

import org.hibernate.validator.HibernateValidatorConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * i18n 配置
 * @author kaka
 * @version v1.0
 * @date 2019/12/24 14:08
 * @since v1.0
 */
@Configuration
public class LocaleConfig {

    @Resource
    private MessageSource messageSource;

    @Resource
    private LocalValidatorFactoryBean localValidatorFactoryBean;

    /**
     * 默认解析器 其中locale表示默认语言
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new XbbLocaleResolver();
//        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
//        // 设置对应的cookie键名
//        localeResolver.setCookieName("xbbLocale");
//        // 设置cookie有效期
//        localeResolver.setCookieMaxAge(3600);
//        localeResolver.setDefaultLocale(Locale.CHINA);
//        return localeResolver;
    }

    /**
     * 默认拦截器 其中lang表示切换语言的参数名
     */
    @Bean
    public WebMvcConfigurer localeInterceptor() {
        return new WebMvcConfigurer() {
            /**
             * 默认拦截器 其中lang表示切换语言的参数名
             * @param registry InterceptorRegistry
             */
//            @Override
//            public void addInterceptors(InterceptorRegistry registry) {
//                LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
//                localeInterceptor.setParamName("lang");
//                registry.addInterceptor(localeInterceptor);
//            }

            /**
             * Hibernate Validator国际化配置
             * @return Validator
             */
            @Override
            public Validator getValidator() {
                //该行代码即指定了使用Spring的国际化配置来配置Hibernate-Validator框架的国际化信息
                localValidatorFactoryBean.setValidationMessageSource(messageSource);
                //该行代码是给Hibernate-Validator框架设置一些参数，比如下面一行设置校验快速失败模式，关于什么是快速失败，我在这里不详细展开，不懂的同学google即可
                localValidatorFactoryBean.getValidationPropertyMap().put(HibernateValidatorConfiguration.FAIL_FAST, "true");
                return localValidatorFactoryBean;
            }
        };
    }
}
